//
//  HomeViewController.m
//  TerritoryShopkeeper
//
//  Created by xiaowu on 2017/11/27.
//  Copyright © 2017年 ZDQK. All rights reserved.
//

#import "HomeViewController.h"
#import "ScanViewController.h"
#import "SearchCacheViewController.h"
#import "GoodsListFiltrateViewController.h"
#import "GoodsListViewController.h"
#import "HomeClassifyView.h"
#import "HomeClassifyModel.h"
#import "TimeUpListViewController.h"
#import "IconPointButton.h"
// cell
#import "HomeFirstCell.h"
#import "HomeBrandCell.h"
#import "HomeBannerImageViewCell.h"
#import "HomeGoodsCollectionCell.h"
#import "HomeGoodsDoubleCell.h"
// model
#import "HomeNoticeItem.h"
#import "HomeClassItem.h"
#import "HomeClassListItem.h"
#import "HomeGoodsItem.h"
// vc
#import "GoodsDetailViewController.h"
#import "IntegralShopViewController.h"
#import "StoresNearbyViewController.h"
#import "CouponViewController.h"
#import "SellAbroadViewController.h"
#import "MineMessageViewController.h"
#import "OtherH5ViewController.h"
#import "DYGJGVC.h"
#import "DYShopListVC.h"

#import "DYESPAuthVC.h"
#import "DYBaseWebVC.h"
#import "UIAlertView+JKBlock.h"

#define Color_Arr [NSArray arrayWithObjects:@[[UIColor colorWithHex:0xD865FF alpha:1.0],[UIColor colorWithHex:0x943BFF alpha:1.0]], @[[UIColor colorWithHex:0xFE4B93 alpha:1.0],[UIColor colorWithHex:0xFB0556 alpha:1.0]], @[[UIColor colorWithHex:0xFFB965 alpha:1.0],[UIColor colorWithHex:0xFF3B3B alpha:1.0]], @[[UIColor colorWithHex:0x65CCFF alpha:1.0],[UIColor colorWithHex:0x3BABFF alpha:1.0]], nil]

@interface HomeViewController ()<UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate, BHInfiniteScrollViewDelegate, UIScrollViewDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *tableViewTop;

@property (nonatomic, strong) UIView *searchView;
@property (nonatomic, strong) UISearchBar *searchBar;

@property (nonatomic, strong) IconPointButton *rightButton;
@property (nonatomic, strong) UIButton *leftButton;

@property (nonatomic, strong) UIView *tableViewHeader;
@property (nonatomic, strong) BHInfiniteScrollView *bannerView;

@property (nonatomic, strong) HomeClassifyView *classifyView;

@property (nonatomic, strong) HomeFirstCell *firstCell;
@property (nonatomic, strong) HomeBrandCell *brandCell;

@property (nonatomic, strong) NSMutableArray *noticeListArr;
@property (nonatomic, strong) NSMutableArray *bannerListArr;
@property (nonatomic, strong) NSMutableArray *middleListArr; // 多种不规则大小的分类数组
@property (nonatomic, strong) NSMutableArray *brandListArr;
@property (nonatomic, strong) NSMutableArray *seckillListArr;
@property (nonatomic, strong) NSMutableArray *otherListArr; //
@property (nonatomic, strong) NSMutableArray *firstArr;

@property (nonatomic, strong) NSMutableArray *goodsItemlistArr;
@property (nonatomic, assign) NSInteger currentPage;
@end

@implementation HomeViewController

- (instancetype)init {
    self = [super init];
    if (self) {
        self.hidesBottomBarWhenPushed = NO;
        self.navigationItem.title = @"首页";
//        _fisrtCell = [[[NSBundle mainBundle] loadNibNamed:@"HomeFirstCell" owner:self options:nil] firstObject];
        _firstCell = [[HomeFirstCell alloc] init];
        _brandCell = [[HomeBrandCell alloc] init];
        
        _noticeListArr = [NSMutableArray array];
        _bannerListArr = [NSMutableArray array];
        _middleListArr = [NSMutableArray array];
        _brandListArr = [NSMutableArray array];
        _seckillListArr = [NSMutableArray array];
        _otherListArr = [NSMutableArray array];
        _goodsItemlistArr = [NSMutableArray array];
        _firstArr = [NSMutableArray array];
        
        _currentPage = 1;
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadRightButton) name:ReciveRongCloudMessage object:nil];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [self configureUI];
    [self responseBlock];
    [self getAllNetWork];
    
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        self.tableViewTop.constant = -[self getNavAndStatusHeight];
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
    self.tableView.mj_insetT = 0;
    [self checkNewVersion];

}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    [self navigationSetup];
}

- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self navigationSetup];
    [self reloadRightButton];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:nil];
}

- (void)navigationSetup {
    [self hideNavigationController];
    [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageWithColor:[UIColor colorWithHex:0xF23030 alpha:self.tableView.mj_offsetY > [self getNavAndStatusHeight]]] forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:[UIImage new]];
    
    if (self.tableView.mj_offsetY > [self getNavAndStatusHeight]) {
        [self setStatusBarStyle:UIStatusBarStyleLightContent animated:YES];
    } else {
        [self setStatusBarStyle:UIStatusBarStyleDefault animated:YES];
    }
}

- (void)reloadRightButton {
    if ([UserInfo shareInstance].user.showBadge) {
        [self.rightButton.redPoint setHidden:NO];
    } else {
        [self.rightButton.redPoint setHidden:YES];
    }
}
#pragma mark - Method
- (void)configureUI {
    [self configureNavigation];
    [self reloadHeaderView];
    [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];

    
    self.view.backgroundColor = [UIColor backgroundColor];
    self.tableView.backgroundColor = [UIColor backgroundColor];
    
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.estimatedRowHeight = [HomeGoodsDoubleCell getHeight];
    [self.tableView clearExtendCellLine];
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"HomeBannerImageViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"imageViewCell"];
    [self.tableView registerClass:[HomeGoodsCollectionCell class] forCellReuseIdentifier:@"goodsCollectionCell"];
    [self.tableView registerClass:[HomeGoodsDoubleCell class] forCellReuseIdentifier:@"doubleCell"];
    
    __weak typeof(self) weakSelf = self;
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        weakSelf.currentPage = 1;
        [weakSelf getAllNetWork];
    }];
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        weakSelf.currentPage += 1;
        [weakSelf getRecommendList];
    }];
}

- (void)configureNavigation {
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"scan"] style:UIBarButtonItemStylePlain target:self action:@selector(leftItemClick)];
    //self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"news"] style:UIBarButtonItemStylePlain target:self action:@selector(rightItemClick)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.rightButton];
    
    [self.searchView addSubview:self.searchBar];
    self.searchView.frame = CGRectMake(0, 0, ScreenWidth - 15 * 4 - 28 * 2, 28);
    self.searchBar.frame = CGRectMake(0, 0, self.searchView.width, 28);
    self.navigationItem.titleView = self.searchView;
}

- (void)reloadHeaderView {
    for (UIView *view in self.tableViewHeader.subviews) {
        if ([view isKindOfClass:[BHInfiniteScrollView class]]) {
            [view removeFromSuperview];
        }
    }
    
    _bannerView = [BHInfiniteScrollView infiniteScrollViewWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenWidth * 0.5) Delegate:self ImagesArray:[self getImagesWithArr:self.bannerListArr] PlageHolderImage:PlaceholderImageBig InfiniteLoop:YES];
    [_bannerView setBackgroundColor:[UIColor imageEDBackgroundColor]];
    
    _bannerView.dotSize = 6;
    _bannerView.dotSpacing = 5;
    _bannerView.pageControlAlignmentOffset = CGSizeMake(0, 10);
    _bannerView.dotColor = [UIColor yellowLineColor];
    _bannerView.selectedDotColor = [UIColor whiteColor];
    
    [self.tableViewHeader addSubview:self.bannerView];
    self.tableViewHeader.frame = CGRectMake(0, 0, ScreenWidth, ScreenWidth * 0.5);
    
    self.tableView.tableHeaderView = self.tableViewHeader;

}

- (void)setClassifyViewData {
    [self.classifyView setValueForViewWithArr:[self configureTestData]];
    [self.classifyView setValueForNoticeItemList:self.noticeListArr];
}

- (void)responseBlock {
    __weak typeof(self) weakSelf = self;
    self.classifyView.block = ^(NSInteger index) {
        switch (index) {
            case 0:{
                // 跨境商品
                GoodsListFiltrateViewController *filtrateVC =[[GoodsListFiltrateViewController alloc] init];
                filtrateVC.gcid = @"";
                filtrateVC.isAbroad = YES;
                [weakSelf.navigationController pushViewController:filtrateVC animated:YES];
            } break;
            case 1:{
                if (![weakSelf checkLogin]) {
                    return;
                }
                // ESP专区
//                GoodsListFiltrateViewController *filtrateVC =[[GoodsListFiltrateViewController alloc] init];
//                filtrateVC.gcid = @"23";
                DYESPAuthVC * filtrateVC = [[DYESPAuthVC alloc] init];
                [weakSelf.navigationController pushViewController:filtrateVC animated:YES];
            } break;
            case 2:{
                if (![weakSelf checkLogin]) {
                    return;
                }
                //店铺
                DYShopListVC *vc = [[DYShopListVC alloc] init];
                [weakSelf.navigationController pushViewController:vc animated:YES];
            } break;
            case 4:{
                // 积分商城
                IntegralShopViewController *integralVC = [[IntegralShopViewController alloc] init];
                [weakSelf.navigationController pushViewController:integralVC animated:YES];
            } break;
            case 3:{
                // 附近门店
                StoresNearbyViewController *storeNearbyVC = [[StoresNearbyViewController alloc] init];
                [weakSelf.navigationController pushViewController:storeNearbyVC animated:YES];
            } break;
            case 5:{
                if (![weakSelf checkLogin]) {
                    return;
                }
                // 优惠券
                CouponViewController *couponVC = [[CouponViewController alloc] init];
                couponVC.type = CouponFromTypeMine;
                [weakSelf.navigationController pushViewController:couponVC animated:YES];
            } break;
            case 6:{
                // 海外代购
//                SellAbroadViewController *sellAbroad = [[SellAbroadViewController alloc] init];
//                [weakSelf.navigationController pushViewController:sellAbroad animated:YES];
                DYGJGVC * vc = [[DYGJGVC  alloc] init];
                [weakSelf.navigationController pushViewController:vc animated:YES];
            } break;
            case 7:{
                // 金融优惠
                if ([weakSelf checkOpen]) {
                    OtherH5ViewController *dzjrVC = [[OtherH5ViewController alloc] init];
                    dzjrVC.title = @"大众金融";
                    dzjrVC.url = @"http://wx.dztcjzg.com";
                    [weakSelf.navigationController pushViewController:dzjrVC animated:YES];
                }
            } break;
            case 8:{
                // 健康厨房
                if ([weakSelf checkOpen]) {
                    
                }
            } break;
            default:
                break;
        }
    };
    
    self.classifyView.noticeBlock = ^(NSInteger index) {
        NSLog(@"notice index = %ld", (long)index);
    };
    
    self.firstCell.block = ^(NSInteger index) {
        HomeClassItem *item = [weakSelf.middleListArr safeObjectAtIndex:index];
        if (index == 1) {
            // 限时抢购
            TimeUpListViewController *timeupListVC = [[TimeUpListViewController alloc] init];
            [weakSelf.navigationController pushViewController:timeupListVC animated:YES];
        } else if (index == 6) {
            // 倒计时结束刷新界面
            if (weakSelf.seckillListArr.count > 0) {
                [weakSelf.seckillListArr removeObjectAtIndex:0];
            }
            [weakSelf reloadUI:weakSelf.seckillListArr];
        } else {
            GoodsListFiltrateViewController *filtrateVC = [[GoodsListFiltrateViewController alloc] init];
            filtrateVC.gtrcid = item.alink;
            [weakSelf.navigationController pushViewController:filtrateVC animated:YES];
        }
    };
    
    self.brandCell.block = ^(NSInteger index) {
        NSLog(@"brand index:%ld", (long)index);
        HomeClassItem *item = [weakSelf.brandListArr objectAtIndex:index];
        GoodsListFiltrateViewController *filtrateVC = [[GoodsListFiltrateViewController alloc] init];
        filtrateVC.gtrcid = item.alink;
        [weakSelf.navigationController pushViewController:filtrateVC animated:YES];
    };
}

- (void)reloadUI:(NSMutableArray *)array {
    [self reloadHeaderView];
    
    double sec = 0;
    if (array.count > 0) {
        HomeClassItem *item = array.firstObject;
        if (item.state == 0) {
            sec = [DateSomeThing getStringWithCurrentTimeStr:item.sktime currentDateFormat:@"HH:mm:ss"];
        } else {
            sec = [DateSomeThing getStringWithCurrentTimeStr:item.endtime currentDateFormat:@"HH:mm:ss"];
        }
    }
    [self.firstCell setValueForCellWithArr:self.middleListArr resetTime:sec];
    
    [self.brandCell setValueForCell:self.brandListArr];
}

- (NSMutableArray *)getImagesWithArr:(NSMutableArray *)listArr {
    NSMutableArray *arr = [NSMutableArray array];
    
    for (HomeClassItem *item in listArr) {
        [arr addObject:item.aimg];
    }
    
    return arr;
}

#pragma mark - Action
- (void)leftItemClick {
    ScanViewController *scanVC = [[ScanViewController alloc] init];
    [self.navigationController pushViewController:scanVC animated:YES];
}

- (void)rightItemClick {
    if ([self checkLogin]) {
        MineMessageViewController *messageVC = [[MineMessageViewController alloc] init];
        [self.navigationController pushViewController:messageVC animated:YES];
    }
}

- (void)gotoSearchVC {
    SearchCacheViewController *searchVC = [[SearchCacheViewController alloc] init];
    [self.navigationController pushViewController:searchVC animated:YES];
}

#pragma mark - 检查更新
- (void)checkNewVersion{
    [MYAFNetworking POST:@"api2/getVersionNumber" parameters:@{@"t":@"1"} success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        NSLog(@"版本信息是：%@",responseObject);
        NSString * code = [responseObject safeObjectForKey:@"code"];
        if ([code isEqualToString:@"200"]) {
            id data = [responseObject safeObjectForKey:@"data"];
            NSString * newVersion = [data safeStringForKey:@"url"];
            NSDictionary *infoDict = [[NSBundle mainBundle] infoDictionary];
            NSString *vison = infoDict[@"CFBundleVersion"];
            if ([vison compare:newVersion options:NSNumericSearch] == NSOrderedDescending){
                NSLog(@"%@ is bigger",vison);
                NSLog(@"有更新");
                [UIAlertView jk_alertWithCallBackBlock:^(NSInteger buttonIndex) {
                    if (buttonIndex == 0) {
                        return;
                    }
                    if ([[[UIDevice currentDevice] systemVersion] floatValue] < 11) {
                        NSString *urlStr = @"itms-apps://ax.itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?type=Purple+Software&id=1366117484";
                        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlStr]];
                    }else{
                        NSString *itunesurl = @"itms-apps://itunes.apple.com/cn/app/id1366117484?mt=8";
                        
                        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:itunesurl]];
                    }
                } title:@"提示" message:[NSString stringWithFormat:@"有新的版本%@",newVersion] cancelButtonName:@"取消" otherButtonTitles:@"更新", nil];
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        NSLog(@"检查更新失败");
    }];
}

#pragma mark - NetWork
- (void)getAllNetWork {
    [self loadNoticeList];
    [self getAdvList];
    [self getMidClassGoods];
    [self getRecommendList];
    [self getFirstClass];
}

- (void)loadNoticeList {
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    
    __weak typeof(self) weakSelf = self;
    [MYAFNetworking POST:URL_Get_Notice parameters:parameters success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        NSDictionary *responseDic = responseObject;
        NSString *code = [responseDic safeStringForKey:@"code"];
        if (code && [code isEqualToString:@"200"]) {
            NSArray *data = [responseDic safeJsonObjectForKey:@"data"];
            [weakSelf.noticeListArr removeAllObjects];
            for (NSDictionary *modelDic in data) {
                HomeNoticeItem *item = [HomeNoticeItem mj_objectWithKeyValues:modelDic];
                [weakSelf.noticeListArr addObject:item];
            }
            [weakSelf setClassifyViewData];
        } else {
            [MBProgressHUD showError:weakSelf.view title:responseObject[@"message"] code:responseObject[@"code"] animated:YES];
        }
        NSLog(@"%@", responseDic);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        
    }];
    
}

- (void)getAdvList {
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    __weak typeof(self) weakSelf = self;
    [MYAFNetworking POST:URL_Get_Mid_advlist parameters:parameters success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        NSDictionary *responseDic = responseObject;
        NSString *code = [responseDic safeStringForKey:@"code"];
        if (code && [code isEqualToString:@"200"]) {
            NSDictionary *dataDic = [responseDic safeJsonObjectForKey:@"data"];
            NSArray *advbanner = [dataDic safeJsonObjectForKey:@"advbanner"];
            
            [weakSelf.bannerListArr removeAllObjects];
            [weakSelf.brandListArr removeAllObjects];
            [weakSelf.middleListArr removeAllObjects];
            [weakSelf.seckillListArr removeAllObjects];
            
            for (NSDictionary *modelDic in advbanner) {
                HomeClassItem *item = [HomeClassItem mj_objectWithKeyValues:modelDic];
                [weakSelf.bannerListArr addObject:item];
            }
            
            NSArray *brand = [dataDic safeJsonObjectForKey:@"adveight"];
            for (NSDictionary *modelDic in brand) {
                HomeClassItem *item = [HomeClassItem mj_objectWithKeyValues:modelDic];
                [weakSelf.brandListArr addObject:item];
            }
            
            NSArray *advtlist = [dataDic safeJsonObjectForKey:@"advtlist"];
            for (NSDictionary *modelDic in advtlist) {
                HomeClassItem *item = [HomeClassItem mj_objectWithKeyValues:modelDic];
                [weakSelf.middleListArr addObject:item];
            }
            
            NSArray *seckilllist = [dataDic safeJsonObjectForKey:@"seckilllist"];
            for (NSDictionary *modelDic in seckilllist) {
                HomeClassItem *item = [HomeClassItem mj_objectWithKeyValues:modelDic];
                CGFloat startMin = [DateSomeThing getStringWithCurrentTimeStr:item.sktime currentDateFormat:@"HH:mm:ss"];
                CGFloat endMin = [DateSomeThing getStringWithCurrentTimeStr:item.endtime currentDateFormat:@"HH:mm:ss"];
                // 0未开始 1抢购中 -1已结束
                if (startMin >= 0) {
                    item.state = 0;
                } else if (startMin < 0 && endMin > 0) {
                    item.state = 1;
                } else if (endMin <= 0) {
                    item.state = -1;
                }
                
                if (item.state >= 0) {
                    [weakSelf.seckillListArr addObject:item];
                }
            }
            
            [weakSelf reloadUI:weakSelf.seckillListArr];
        } else {
            [MBProgressHUD showError:weakSelf.view title:responseObject[@"message"] code:responseObject[@"code"] animated:YES];
        }
        NSLog(@"responseDic:%@", responseDic);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        
    }];
    
}

- (void)getMidClassGoods {
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    __weak typeof(self) weakSelf = self;
    [MYAFNetworking POST:URL_Get_Home_classgoods parameters:parameters success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        NSDictionary *responseDic = responseObject;
        NSString *code = [responseDic safeStringForKey:@"code"];
        if (code && [code isEqualToString:@"200"]) {
            NSArray *data = [responseDic safeJsonObjectForKey:@"data"];
            [weakSelf.otherListArr removeAllObjects];
            for (NSDictionary *modelDic in data) {
                HomeClassListItem *listItem = [HomeClassListItem mj_objectWithKeyValues:modelDic];
                [weakSelf.otherListArr addObject:listItem];
            }
            [weakSelf.tableView reloadData];
        }
        NSLog(@"responseDic:%@", responseDic);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        
    }];
}

- (void)getRecommendList {
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters safeSetObject:@(self.currentPage) forKey:@"pageNumber"];
    [parameters safeSetObject:PageSize forKey:@"pageSize"];
    __weak typeof(self) weakSelf = self;
    [MYAFNetworking POST:URL_Get_Home_Recommend parameters:parameters success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        [weakSelf.tableView.mj_header endRefreshing];
        [weakSelf.tableView.mj_footer endRefreshing];
        
        NSDictionary *responseDic = responseObject;
        NSString *code = [responseDic safeStringForKey:@"code"];
        if (code && [code isEqualToString:@"200"]) {
            NSDictionary *data = [responseDic safeJsonObjectForKey:@"data"];
            NSArray *list = [data safeJsonObjectForKey:@"list"];
            NSString *pageNumber = [data safeStringForKey:@"pageNumber"];
            NSString *totalPage = [data safeStringForKey:@"totalPage"];
            
            if ([pageNumber isEqualToString:totalPage]) {
                [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
            } else {
                [weakSelf.tableView.mj_footer resetNoMoreData];
            }
            
            if ([pageNumber isEqualToString:@"1"]) {
                [weakSelf.goodsItemlistArr removeAllObjects];
            }
            
            for (NSDictionary *modelDic in list) {
                HomeGoodsItem *item = [HomeGoodsItem mj_objectWithKeyValues:modelDic];
                [weakSelf.goodsItemlistArr addObject:item];
            }
            
            [weakSelf.tableView reloadData];
        }
        NSLog(@"responseDic:%@", responseDic);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        [weakSelf.tableView.mj_header endRefreshing];
        [weakSelf.tableView.mj_footer endRefreshing];
    }];
}
- (void)getFirstClass {
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [MBProgressHUD showHUDProgress:self.view animated:YES];
    
    __weak typeof(self) weakSelf = self;
    [MYAFNetworking POST:URL_Get_All_Class parameters:parameters success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        NSDictionary *responseDic = responseObject;
        NSString *code = [responseDic safeStringForKey:@"code"];
        if (code && [code isEqualToString:@"200"]) {
            NSArray *data = [responseDic safeJsonObjectForKey:@"data"];
            [weakSelf.firstArr removeAllObjects];
            for (NSDictionary *modelDic in data) {
                ClassifyFirstModel *model = [ClassifyFirstModel mj_objectWithKeyValues:modelDic];
                [weakSelf.firstArr addObject:model];
            }
        } else {
            [MBProgressHUD showError:weakSelf.view title:[responseDic safeStringForKey:@"message"] code:nil animated:YES];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        [MBProgressHUD showError:weakSelf.view title:@"" code:nil animated:YES];
    } isNeedCache:NO];
}

#pragma mark - UISearchBarDelegate
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {
    SearchCacheViewController *searchCacheVC = [[SearchCacheViewController alloc] init];
    searchCacheVC.type = SearchCacheViewControllerTypeForSearch;
    [self.navigationController pushViewController:searchCacheVC animated:YES];
    return NO;
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3 + self.otherListArr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 1;
    } else if (section == 1) {
        return self.brandListArr.count > 0 ? 1 : 0;
    } else if (section == (1 + 1 + self.otherListArr.count)) {
        return [HomeGoodsDoubleCell getRowNumberWithItemArr:self.goodsItemlistArr];
    } else {
        return 2;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    __weak typeof(self) weakSelf = self;
    if (indexPath.section == 0) {
        return self.firstCell;
    } else if (indexPath.section == 1) {
        return self.brandCell;
    } else if (indexPath.section == (1 + 1 + self.otherListArr.count)) {
        HomeGoodsDoubleCell *doubleCell = [tableView dequeueReusableCellWithIdentifier:@"doubleCell" forIndexPath:indexPath];
        NSArray *arr =  [HomeGoodsDoubleCell getCellItemArr:self.goodsItemlistArr withRow:indexPath.row];
        [doubleCell setValuesForCellWithItems:arr];
        doubleCell.block = ^(NSInteger index) {
            HomeGoodsItem *item = [arr safeObjectAtIndex:index];
            if (!item.isshelves) {
                [MBProgressHUD showError:weakSelf.view title:@"该商品已下架" code:@"" animated:YES];
                return;
            }
            GoodsDetailViewController *goodsDetailVC = [[GoodsDetailViewController alloc] init];
            goodsDetailVC.gid = item.gid;
            [weakSelf.navigationController pushViewController:goodsDetailVC animated:YES];
        };
        return doubleCell;
    } else {
        HomeClassListItem *listItem = [self.otherListArr safeObjectAtIndex:(indexPath.section - 2)];
        
        if (indexPath.row == 0) {
            HomeBannerImageViewCell *imageViewCell = [tableView dequeueReusableCellWithIdentifier:@"imageViewCell" forIndexPath:indexPath];
            [imageViewCell.iconImageVIew sd_setImageWithURL:[NSURL URLWithString:listItem.gtrpimg] placeholderImage:PlaceholderImageBig changeContentModel:UIViewContentModeScaleAspectFill];
            return imageViewCell;
        } else {
            HomeGoodsCollectionCell *collectionCell = [tableView dequeueReusableCellWithIdentifier:@"goodsCollectionCell" forIndexPath:indexPath];
            
            [collectionCell setValueForCellWithListArr:listItem.goods];
            collectionCell.block = ^(NSInteger index) {
                NSLog(@"ahha");
                HomeGoodsItem *item = [listItem.goods safeObjectAtIndex:index];
                if (!item.isshelves) {
                    [MBProgressHUD showError:weakSelf.view title:@"该商品已下架" code:@"" animated:YES];
                    return;
                }
                GoodsDetailViewController *goodsDetailVC = [[GoodsDetailViewController alloc] init];
                goodsDetailVC.gid = item.gid;
                [weakSelf.navigationController pushViewController:goodsDetailVC animated:YES];

            };
            return collectionCell;
        }
    }
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.section <= 1 && (indexPath.section == 2 + self.otherListArr.count)) {
        return;
    }
    HomeClassListItem *listItem = [self.otherListArr safeObjectAtIndex:(indexPath.section - 2)];
    if (indexPath.row == 0) {
        if (TextIsNotNil(listItem.gcurl)) {
            OtherH5ViewController *h5VC = [[OtherH5ViewController alloc] init];
            h5VC.title = listItem.gcname;
            h5VC.url = listItem.gcurl;
            [self.navigationController pushViewController:h5VC animated:YES];
        } else {
            GoodsListFiltrateViewController *filtrateVC = [[GoodsListFiltrateViewController alloc] init];
            filtrateVC.gcid = listItem.gcid;
            filtrateVC.gtcid = listItem.gtcid;
            filtrateVC.gtrcid = listItem.gtrcid;
            [self.navigationController pushViewController:filtrateVC animated:YES];
        }
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return [HomeFirstCell getHeight];
    } else if (indexPath.section == 1) {
        return self.brandListArr.count > 0 ? [HomeBrandCell getHeight] : 0;
    } else if (indexPath.section == (1 + 1 + self.otherListArr.count)) {
        return [HomeGoodsDoubleCell getHeight];
    } else {
        HomeClassListItem *listItem = [self.otherListArr safeObjectAtIndex:(indexPath.section - 2)];
        if (indexPath.row == 0) {
            return ScreenWidth / 2.5;
        } else {
            return [HomeGoodsCollectionCell getHeightWithArr:listItem.goods];
        }
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return self.classifyView;
    } else {
        UIView *view = [UIView new];
        view.backgroundColor = [UIColor clearColor];
        UILabel *label = [[UILabel alloc] init];
        
        label.textAlignment = NSTextAlignmentCenter;
        label.frame = CGRectMake(0, 0, 100, 30);
        label.textColor = [UIColor whiteColor];

        [label setGradientHorizontal:@[[UIColor colorWithHex:0xFFB965 alpha:1.0],[UIColor colorWithHex:0xFF3B3B alpha:1.0]]];
        [label addRoundedCorners:(UIRectCornerTopRight | UIRectCornerBottomRight) withRadii:CGSizeMake(100, 30)];

        if (section == 1) {
            if (self.brandListArr.count == 0) {
                return [UIView new];
            }
            [label setGradientHorizontal:@[[UIColor colorWithHex:0xD865FF alpha:1.0],[UIColor colorWithHex:0x943BFF alpha:1.0]]];
            label.text = @"精选专场";
        } else if (section == (2 + self.otherListArr.count)) {
            [label setGradientHorizontal:@[[UIColor colorWithHex:0x65CCFF alpha:1.0],[UIColor colorWithHex:0x3BABFF alpha:1.0]]];
            label.text = @"为你推荐";
        } else {
            
            [label setGradientHorizontal:[Color_Arr objectAtIndex:((section + 1) % 4)]];

            HomeClassListItem *listItem = [self.otherListArr safeObjectAtIndex:(section - 2)];
            label.text = listItem.gcname;
        }
        [view addSubview:label];

        return view;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return [HomeClassifyView getHeightWithArr:[self configureTestData]];
    } else {
        if (section == 1 && self.brandListArr.count == 0) {
            return 0.1;
        }
        return 10;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *footer = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 10)];
    footer.backgroundColor = [UIColor clearColor];
    return footer;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if ((section == 1 && self.brandListArr.count == 0) || (section == (1 + 1 + self.otherListArr.count))) {
        return 0.1;
    }
    return 10;
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    //NSLog(@"y=%f", scrollView.mj_offsetY);
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageWithColor:[UIColor colorWithHex:0xF23030 alpha:(scrollView.mj_offsetY > [self getNavAndStatusHeight] ? 1 : (scrollView.mj_offsetY * 1.0 / [self getNavAndStatusHeight]))]] forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:[UIImage new]];
//    if (scrollView.mj_offsetY > 0) {
//    } else
//
    if (scrollView.mj_offsetY < 0) {
        [self setNavigationBarAlpha:0 animation:YES];
        [self setStatusBarStyle:UIStatusBarStyleDefault animated:YES];
    } else if (scrollView.mj_offsetY == 0) {
        [self setNavigationBarAlpha:1 animation:YES];
        [self setStatusBarStyle:UIStatusBarStyleDefault animated:YES];
    } else {
        [self setNavigationBarAlpha:1 animation:YES];
        [self setStatusBarStyle:UIStatusBarStyleLightContent animated:YES];
    }
}
#pragma mark - BHInfiniteScrollViewDelegate
- (void)infiniteScrollView:(BHInfiniteScrollView *)infiniteScrollView didSelectItemAtIndex:(NSInteger)index {
    HomeClassItem *item = self.bannerListArr[index];
    if (TextIsNotNil(item.alink)) {
//        OtherH5ViewController *h5VC = [[OtherH5ViewController alloc] init];
//        h5VC.title = item.atitle;
//        h5VC.url = item.alink;
        id data = @{
                    @"url": item.alink,
                    };
        DYBaseWebVC * h5VC = [[DYBaseWebVC alloc] initWithData:data];
        h5VC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:h5VC animated:YES];
    }
}
#pragma mark - Getters
- (IconPointButton *)rightButton {
    if (!_rightButton) {
        _rightButton = [IconPointButton buttonWithType:UIButtonTypeCustom];
        [_rightButton setFrame:CGRectMake(0, 0, 28, 28)];
        [_rightButton setImage:[UIImage imageNamed:@"news"] forState:UIControlStateNormal];
        [_rightButton addTarget:self action:@selector(rightItemClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _rightButton;
}

- (UIView *)searchView {
    if (!_searchView) {
        _searchView = [[UIView alloc] init];
        [_searchView.layer setCornerRadius:14];
        _searchView.clipsToBounds = YES;
        [_searchView setBackgroundColor:[UIColor whiteColor]];
    }
    return _searchView;
}

- (UISearchBar *)searchBar {
    if (!_searchBar) {
        _searchBar = [[UISearchBar alloc] init];
        _searchBar.delegate = self;
        [_searchBar setTintColor:[UIColor blueColor]];
        _searchBar.backgroundImage = [UIImage imageWithColor:[UIColor whiteColor]];
        //[_searchBar changeLeftPlaceholder:@"搜索你想要的"];
        _searchBar.placeholder = @"搜索你感兴趣的商品";
        
        UITextField *searchField = [_searchBar valueForKey:@"searchField"];
        searchField.mj_h = 28;
        [searchField.layer setCornerRadius:14];
        //[searchField.layer setBorderWidth:0.5];
        [searchField.layer setBorderColor:[UIColor lightGrayColor].CGColor];
        searchField.layer.masksToBounds = YES;
        searchField.font = TextPingFangFontSize(14);
        
    }
    return _searchBar;
}

- (UIView *)tableViewHeader {
    if (!_tableViewHeader) {
        _tableViewHeader = [[UIView alloc] init];
    }
    return _tableViewHeader;
}

- (HomeClassifyView *)classifyView {
    if (!_classifyView) {
        _classifyView = [[HomeClassifyView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenWidth)];
    }
    return _classifyView;
}

- (NSMutableArray *)configureTestData {
    NSMutableArray *data = [NSMutableArray array];
    HomeClassifyModel *classifyModel1 = [[HomeClassifyModel alloc] init];
    classifyModel1.name = @"跨境商品";
    classifyModel1.image = @"border";
    
    HomeClassifyModel *classifyModel2 = [[HomeClassifyModel alloc] init];
    classifyModel2.name = @"ESP专区";
    classifyModel2.image = @"member";
    
    HomeClassifyModel *dp = [[HomeClassifyModel alloc] init];
    dp.name = @"店铺";
    dp.image = @"er_shop_home";
    
    HomeClassifyModel *classifyModel3 = [[HomeClassifyModel alloc] init];
    classifyModel3.name = @"积分商城";
    classifyModel3.image = @"integral";

    HomeClassifyModel *classifyModel4 = [[HomeClassifyModel alloc] init];
    classifyModel4.name = @"附近门店";
    classifyModel4.image = @"store";

    HomeClassifyModel *classifyModel5 = [[HomeClassifyModel alloc] init];
    classifyModel5.name = @"优惠券";
    classifyModel5.image = @"coupon";
    
    HomeClassifyModel *classifyModel6 = [[HomeClassifyModel alloc] init];
    classifyModel6.name = @"国际行邮";
    classifyModel6.image = @"澳洲代购";
    
    HomeClassifyModel *classifyModel7 = [[HomeClassifyModel alloc] init];
    classifyModel7.name = @"大众金融";
    classifyModel7.image = @"澳洲团购";
    
    HomeClassifyModel *classifyModel8 = [[HomeClassifyModel alloc] init];
    classifyModel8.name = @"大象鲜生";
    classifyModel8.image = @"健康厨房logo";

    [data addObject:classifyModel1];
    [data addObject:classifyModel2];
    [data addObject:dp];
//    [data addObject:classifyModel3];
    [data addObject:classifyModel4];
//    [data addObject:classifyModel5];
//    [data addObject:classifyModel6];

    if ([UserInfo shareInstance].isOpen) {
        [data addObject:classifyModel7];
        [data addObject:classifyModel8];
    }
    
    return data;
}

#pragma mark -
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:ReciveRongCloudMessage object:nil];
}


@end
